package com.apotik.legenda.dialog;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellRenderer;

import com.apotik.legenda.custom.TableModelCustom;
import com.apotik.legenda.dao.CustomerDao;
import com.apotik.legenda.dao.SalesTrxDao;
import com.apotik.legenda.model.Customer;
import com.apotik.legenda.model.SalesTrx;
import com.apotik.legenda.model.User;
import com.apotik.legenda.observer.PosObserver;

import javax.swing.JButton;
import javax.swing.JComboBox;

import java.awt.GridLayout;
import java.awt.Color;

public class InputCustomerDialog extends JDialog implements KeyListener, ActionListener {
	private static final long serialVersionUID = 1L;
	
	private static final String TEXT_NEW = "New";
	private static final String TEXT_SEARCH = "Cari";
	
	private JButton btnNew;
	private JButton btnPaginPrev;
	private JButton btnPaginNext;
	private JButton btnSubmit;
	private JButton btnCancel;
	
	private JLabel lblCari;
	private JLabel lblNama; 
	private JLabel lblNoHandphone;
	
	private JTextField textFieldCari;
	private JTextField textFieldNama;
	private JTextField textFieldHp;
	
	private TableModelCustom tableModel;
	private JTable table;
	
	@SuppressWarnings("rawtypes")
	private DefaultComboBoxModel comboboxModel;
	
	@SuppressWarnings("rawtypes")
	private JComboBox comboBox;
	
	private PosObserver observer;
	private SalesTrx st;
	private Customer custSelected = null;
	private int modelRow  = -1;
	private int sizePage = 0;
	
	public InputCustomerDialog(PosObserver observer, SalesTrx st) {
		this.observer = observer;
		this.st = st;
		
		int widthFrame = 500;
		
		setTitle("Passien / Pelanggan");
		setSize(widthFrame, 320);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		addKeyListener(this);
		
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((dim.width-widthFrame)/2, 100);
		
		JPanel panelNorth = panelNorth();
		getContentPane().add(panelNorth, BorderLayout.NORTH);
		
		JPanel panelCenter = panelCenter();
		getContentPane().add(panelCenter, BorderLayout.CENTER);
		
		JPanel panelSouth = panelSouth();
		getContentPane().add(panelSouth, BorderLayout.SOUTH);
		
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private JPanel panelNorth(){
		JPanel panel = new JPanel();
		panel.setBorder(new EmptyBorder(5, 0, 5, 0));
		panel.setLayout(new BorderLayout());
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.WEST);
		
		btnNew = new JButton("New");
		panel_1.add(btnNew);
		btnNew.addActionListener(this);
		
		JLabel lblS1 = new JLabel("|");
		lblS1.setForeground(Color.GRAY);
		lblS1.setFont(new Font("Tahoma", Font.PLAIN, 15));
		panel_1.add(lblS1);
		
		lblCari = new JLabel("Cari:  ");
		lblCari.setFont(new Font("Tahoma", Font.PLAIN, 15));
		panel_1.add(lblCari);
		
		textFieldCari = new JTextField();
		textFieldCari.addKeyListener(this);
		textFieldCari.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textFieldCari.setHorizontalAlignment(SwingConstants.LEFT);
		textFieldCari.setColumns(14);
		panel_1.add(textFieldCari);
		
		JPanel panel_2 = new JPanel();
		panel.add(panel_2, BorderLayout.EAST);
		
		btnPaginPrev = new JButton("<");
		btnPaginPrev.addActionListener(this);
		panel_2.add(btnPaginPrev);
				
		comboboxModel = new DefaultComboBoxModel(paginationContent());
		
		comboBox = new JComboBox();
		comboBox.setModel(comboboxModel);
		comboBox.addActionListener(this);
		panel_2.add(comboBox);
		
		btnPaginNext = new JButton(">");
		btnPaginNext.addActionListener(this);
		panel_2.add(btnPaginNext);
		
		return panel;
	}
	
	private JPanel panelCenter(){
		JPanel panel = new JPanel(new BorderLayout());
		
		JScrollPane panel_1 = scrollPane();
		panel.add(panel_1, BorderLayout.CENTER);
		
		return panel;
	}
	
	@SuppressWarnings("serial")
	private JScrollPane scrollPane(){
		JScrollPane scrollPane = new JScrollPane();
		
		String[] columnNames = {"No.", "Nama", "No. Handphone"};
		tableModel = new TableModelCustom(columnNames);
		loadData(0);
		
		table = new JTable(){
			@Override
			public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
				JLabel label = (JLabel) super.prepareRenderer(renderer, row, column);
				
				if(column==0){
					label.setHorizontalAlignment(JLabel.CENTER);
				}
				
				return label;
			}
		};
		table.setModel(tableModel);
		table.setEnabled(true);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@SuppressWarnings("rawtypes")
			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				int viewRow = table.getSelectedRow();
				if(viewRow>-1){
					modelRow = table.convertRowIndexToModel(viewRow);
					
					Vector v = (Vector) tableModel.getRowVector().get(modelRow);
					if(v!=null){
						custSelected = (Customer) v.get(v.size()-1);
						textFieldNama.setText(custSelected.getFullName());
						textFieldHp.setText(custSelected.getPhoneNumber());
					}
					
				}
			}
		});
		scrollPane.setViewportView(table);
		
		return scrollPane;
	}
	
	private JPanel panelSouth(){
		JPanel panel = new JPanel();
		panel.setBorder(new EmptyBorder(4, 4, 4, 0));
		BorderLayout bl_panel = new BorderLayout();
		bl_panel.setHgap(3);
		panel.setLayout(bl_panel);
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_3 = new JPanel();
		panel_1.add(panel_3);
		panel_3.setLayout(new GridLayout(0, 2, 0, 3));
		
		lblNama = new JLabel("Nama");
		lblNama.setEnabled(false);
		lblNama.setFont(new Font("Tahoma", Font.PLAIN, 12));
		panel_3.add(lblNama);
		
		textFieldNama = new JTextField();
		textFieldNama.setEnabled(false);
		textFieldNama.setFont(new Font("Tahoma", Font.PLAIN, 12));
		panel_3.add(textFieldNama);
		textFieldNama.setColumns(10);
		
		lblNoHandphone = new JLabel("No. Handphone");
		lblNoHandphone.setEnabled(false);
		lblNoHandphone.setFont(new Font("Tahoma", Font.PLAIN, 12));
		panel_3.add(lblNoHandphone);
		
		textFieldHp = new JTextField();
		textFieldHp.setEnabled(false);
		textFieldHp.setFont(new Font("Tahoma", Font.PLAIN, 12));
		panel_3.add(textFieldHp);
		textFieldHp.setColumns(10);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new EmptyBorder(3, 0, 3, 9));
		panel.add(panel_2, BorderLayout.EAST);
		panel_2.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_4 = new JPanel();
		panel_2.add(panel_4, BorderLayout.NORTH);
		
		btnSubmit = new JButton("Submit");
		panel_4.add(btnSubmit);
		btnSubmit.addActionListener(this);
		btnSubmit.setFont(new Font("Tahoma", Font.PLAIN, 13));
		
		btnCancel = new JButton("Cancel");
		panel_4.add(btnCancel);
		btnCancel.addActionListener(this);
		btnCancel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		
		
		return panel;
	}
	
	private String[] paginationContent(){
		CustomerDao dao = new CustomerDao();
		
		int sizeRow = dao.size(true, true);
		int divide = sizeRow/10;
		int mod = sizeRow % 10;
		sizePage = divide;
		if(mod!=0){
			sizePage = divide + 1;
		}
		
		String[] result = new String[sizePage];
		for(int i=0;i<sizePage;i++){
			result[i] = Integer.toString(i+1);
		}
		
		return result;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void loadData(int start){
		tableModel.removeRowAll();
		
		CustomerDao dao = new CustomerDao();
		
		List<Customer> list = dao.listByActiveLimit(true, start, 10);
		if(list.size()>0){
			int i = start+1;
			for(Customer d : list){
				Vector v = new Vector();
				v.add(i);
				v.add(d.getFullName());
				v.add(d.getPhoneNumber()!=null ? d.getPhoneNumber():"");
				v.add(d);
				tableModel.insertData(v);
				i++;
			}
		}
	}
	

	@Override
	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource();
		if(obj==btnNew){
			String text = btnNew.getText();
			if(text.equalsIgnoreCase(TEXT_NEW)){
				btnNew.setText("Cari");
				lblCari.setEnabled(false);
				textFieldCari.setEnabled(false);
				btnPaginPrev.setEnabled(false);
				btnPaginNext.setEnabled(false);
				comboBox.setEnabled(false);
				table.setEnabled(false);
				lblNama.setEnabled(true);
				textFieldNama.setEnabled(true);
				lblNoHandphone.setEnabled(true);
				textFieldHp.setEnabled(true);
			}else if(text.equalsIgnoreCase(TEXT_SEARCH)){
				btnNew.setText("New");
				lblCari.setEnabled(true);
				textFieldCari.setEnabled(true);
				btnPaginPrev.setEnabled(true);
				btnPaginNext.setEnabled(true);
				comboBox.setEnabled(true);
				table.setEnabled(true);
				lblNama.setEnabled(false);
				textFieldNama.setEnabled(false);
				lblNoHandphone.setEnabled(false);
				textFieldHp.setEnabled(false);
			}
			
		}else if(obj==btnPaginPrev){
			int activePageInt = comboBox.getSelectedIndex();
			if(activePageInt!=0){
				int minusOne = activePageInt-1;
				comboBox.setSelectedIndex(minusOne);
				
				int start = 0;
				String[] paginContent = paginationContent();
				for(int i=0;i<paginContent.length;i++){
					if(i==minusOne){
						start = i*10;
					}
				}
				
				loadData(start);
				
			}
		}else if(obj==btnPaginNext){
			int activePageInt = comboBox.getSelectedIndex();
			int plusOne = activePageInt+1;
			if((plusOne)!=sizePage){
				comboBox.setSelectedIndex(plusOne);
				
				int start = 0;
				String[] paginContent = paginationContent();
				for(int i=0;i<paginContent.length;i++){
					if(i==plusOne){
						start = i*10;
					}
				}
				
				loadData(start);
			}
		}else if(obj==comboBox){
			int activePageInt = comboBox.getSelectedIndex();
			int start = activePageInt * 10;
			loadData(start);
		}else if(obj==btnCancel){
			this.setVisible(false);
		}else if(obj==btnSubmit){
			SalesTrx st = this.st;
			
			String text = btnNew.getText();
			if(text.equalsIgnoreCase(TEXT_NEW)){
				String nama = textFieldNama.getText().trim();
				String hp = textFieldHp.getText().trim();
				
				if(nama.isEmpty()){
					st.setCustomer(null);
				}else{
					CustomerDao dao = new CustomerDao();
					
					Customer checkExisting = dao.byNameAndHandphone(nama, hp);
					if(checkExisting==null){
						Calendar cal = Calendar.getInstance();
						User user = st.getCreatedBy();
						
						Customer cust = new Customer();
						cust.setFullName(nama);
						cust.setPhoneNumber(hp);
						cust.setCreatedDate(cal.getTime());
						cust.setUpdatedDate(cal.getTime());
						cust.setActive(true);
						cust.setCreatedBy(user);
						
						if(dao.addNewOrUpdate(cust)){
							Customer gCust = dao.byNameAndHandphone(nama, hp);
							st.setCustomer(gCust);
						}
					}else{
						st.setCustomer(checkExisting);
					}
				}
			}else if(text.equalsIgnoreCase(TEXT_SEARCH)){
				st.setCustomer(custSelected);
			}
			
			SalesTrxDao stDao = new SalesTrxDao();
			if(stDao.saveOrUpdate(st)){
				this.st = st;
				HashMap<String, Object> hm = new HashMap<>();
				hm.put("_st", st);
				observer.insertCustomer(hm);
				InputCustomerDialog.this.setVisible(false);
			}
			
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void keyPressed(KeyEvent ke) {
		if(ke.getKeyCode()==KeyEvent.VK_ESCAPE){
			this.setVisible(false);
		}
		
		Object obj = ke.getSource();
		
		if(obj==textFieldCari){
			if(ke.getKeyCode()==KeyEvent.VK_ENTER){
				String param = textFieldCari.getText();
				if(param.trim().equalsIgnoreCase("")){
					loadData(0);
				}else{
					CustomerDao dao = new CustomerDao();
					List<Customer> list = dao.search(true, param);
					tableModel.removeRowAll();
					if(list.size()>0){
						int i = 1;
						for(Customer d : list){
							Vector v = new Vector();
							v.add(i);
							v.add(d.getFullName());
							v.add(d.getPhoneNumber()!=null ? d.getPhoneNumber():"");
							v.add(d);
							tableModel.insertData(v);
							i++;
						}
					}else{
						JOptionPane.showMessageDialog(null, param+" not found", "Exception", JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
	}

}
